'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');

class UserService extends Service {
    /**
     * 根据分页和搜索条件获取用户信息
     * @param {Object} where 查询用户的条件
     * @param {Number} page 当前分页
     * @param {Number} pageSize 当前页每页多少条
     */
    async getUserRolePermissions(where, page, pageSize) {
        const { Member } = this.ctx.model;
        return Member.findAndCountAll({
            attributes: { exclude: ['password'] },
            where: {
                ...where,
            },
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
    }
    /**
     * 注册用户数据
     * @param {Object} data
     */
    async registerUser(data) {
        const { Member } = this.ctx.model;
        if (!data.phone) {
            throw new Error('请输入手机号');
        }
        // 正则校验手机号
        const phoneReg = /^1[3-9]\d{9}$/;
        if (!phoneReg.test(data.phone)) {
            throw new Error('手机号格式不正确');
        }
        const userExists = await Member.findOne({
            attributes: ['id'],
            where: {
                phone: data.phone,
            },
        });
        if (userExists) throw new Error('该账号已经存在');
        const newUser = await Member.create(data);
        return newUser.dataValues;
    }

    /**
     * 根据条件查询用户信息
     * @param {Object} user
     */
    async loginByEmail({ phone, password }) {
        const { Member } = this.ctx.model;
        // 根据邮箱查询用户是否存在
        let user = await Member.findOne({
            where: { phone },
        });
        if (!user) throw new Error('账号不存在');
        // 判断密码是否有误
        const isValid = user.password === password
        if (!isValid) {
            throw new Error('密码错误');
        }
        user = user.dataValues;
        delete user.password;
        return user;
    }

    async findOne(id) {
        return this.ctx.model.Member.findOne({
            where: {
                id,
            },
        });
    }

    /**
     * 根据id删除对应的用户
     * @param {Number} uid
     */
    async deleteUserById(id) {
        // 删除前先删除地址
        await this.ctx.model.Address.destroy({ where: { member_id: id } });
        // 删除成功在删除用户
        return await this.ctx.model.Member.destroy({ where: { id } });
    }

    /**
     * 根据ID修改用户信息
     * @param {Number} id 用户ID
     * @param {Object} data 要修改的用户信息
     */
    async updateUserById(id, data) {
        const { Member } = this.ctx.model;
        const { phone } = data;
        const andWhere = { id: { [Op.ne]: id } };
        let neenCheck = false;
        if (phone) {
            neenCheck = true;
            andWhere.phone = phone;
        }

        if (neenCheck) {
            const userExists = await Member.findOne({
                attributes: ['id'],
                where: { [Op.and]: andWhere },
            });
            if (userExists) throw new Error('该手机号已注册');
        }

        return await Member.update(data, { where: { id } });
    }
    /**
     * 更新用户密码
     * @param {Number} id 用户ID
     * @param {Object} data 新密码和旧密码
     */
    async updatePassword(id, data) {
        const { Member } = this.ctx.model;
        const user = await Member.findByPk(id);
        if (!user) {
            throw new Error('该手机号不存在');
        }

        // 旧密码是否有误, 正确就直接修改
        const isValid = bcrypt.compareSync(data.old_password, user.password);
        if (!isValid) {
            throw new Error('旧密码输入不正确');
        }
        user.password = data.new_password;
        return await user.save();
    }

    // 所有列表
    async allList(where) {
        const { Member } = this.ctx.model;
        return Member.findAll({
            where,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
        });
    }
}

module.exports = UserService;
